import React, { useState } from 'react';
import { Card, List, Badge, Button, Input, Avatar, Tag, Empty, Tabs, message, Space, Dropdown } from 'antd';
import { MailOutlined, DeleteOutlined, CheckOutlined, StarOutlined, MoreOutlined } from '@ant-design/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { authApi } from '@/api/auth';

const { Search } = Input;

interface MessageItem {
  id: string;
  sender: string;
  subject: string;
  content: string;
  read: boolean;
  starred: boolean;
  createdAt: string;
  attachments?: Array<{
    name: string;
    size: string;
    type: string;
  }>;
}

const MessagesPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('inbox');
  const [searchText, setSearchText] = useState('');
  const queryClient = useQueryClient();

  // 获取消息列表
  const { data: messagesData, isLoading } = useQuery({
    queryKey: ['messages', activeTab],
    queryFn: async () => {
      const params = activeTab === 'unread' ? { page: 1, size: 20 } : { page: 1, size: 20 };
      const response = await authApi.getMessages(params);
      return response;
    },
  });

  // 标记消息为已读
  const markAsReadMutation = useMutation({
    mutationFn: async (_id: string) => {
      // 这里需要在 API 中添加标记消息已读功能
      message.success('已标记为已读');
      queryClient.invalidateQueries({ queryKey: ['messages'] });
    },
  });

  // 删除消息
  const deleteMessageMutation = useMutation({
    mutationFn: async (_id: string) => {
      // 这里需要在 API 中添加删除消息功能
      message.success('消息已删除');
      queryClient.invalidateQueries({ queryKey: ['messages'] });
    },
  });

  // 标星消息
  const starMessageMutation = useMutation({
    mutationFn: async (_id: string) => {
      // 这里需要在 API 中添加标星功能
      message.success('已添加星标');
      queryClient.invalidateQueries({ queryKey: ['messages'] });
    },
  });

  // 处理标记已读
  const handleMarkAsRead = (id: string) => {
    markAsReadMutation.mutate(id);
  };

  // 处理删除消息
  const handleDeleteMessage = (id: string) => {
    deleteMessageMutation.mutate(id);
  };

  // 处理标星
  const handleStarMessage = (id: string) => {
    starMessageMutation.mutate(id);
  };

  // 搜索过滤
  const filterMessages = (messages: MessageItem[]) => {
    return messages.filter(message => {
      if (!searchText) return true;
      const searchLower = searchText.toLowerCase();
      return (
        message.subject.toLowerCase().includes(searchLower) ||
        message.sender.toLowerCase().includes(searchLower) ||
        message.content.toLowerCase().includes(searchLower)
      );
    });
  };

  const messages = messagesData?.items || [];
  const unreadCount = messagesData?.unreadCount || 0;

  const filteredMessages = filterMessages(
    activeTab === 'unread'
      ? messages.filter(m => !m.read)
      : activeTab === 'starred'
      ? messages.filter(m => m.starred)
      : messages
  );

  // 消息操作菜单
  const getMessageMenu = (message: MessageItem) => ({
    items: [
      {
        key: 'read',
        icon: <CheckOutlined />,
        onClick: () => handleMarkAsRead(message.id),
        disabled: message.read,
        label: '标记已读',
      },
      {
        key: 'star',
        icon: <StarOutlined />,
        onClick: () => handleStarMessage(message.id),
        label: message.starred ? '取消星标' : '添加星标',
      },
      {
        type: 'divider' as const,
      },
      {
        key: 'delete',
        icon: <DeleteOutlined />,
        onClick: () => handleDeleteMessage(message.id),
        danger: true,
        label: '删除',
      },
    ],
  });

  return (
    <div style={{ height: '100%', width: '100%' }}>
      <Card
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <MailOutlined />
            消息中心
            {unreadCount > 0 && (
              <Badge count={unreadCount} style={{ backgroundColor: '#ff4d4f' }} />
            )}
          </div>
        }
        style={{ height: '100%' }}
        extra={
          <Space>
            <Search
              placeholder="搜索消息..."
              allowClear
              style={{ width: 200 }}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={(value) => setSearchText(value)}
            />
            <Button type="primary">
              撰写消息
            </Button>
          </Space>
        }
        loading={isLoading}
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            {
              key: 'inbox',
              label: `收件箱`,
              children: null,
            },
            {
              key: 'unread',
              label: (
                <span>
                  未读消息
                  {unreadCount > 0 && (
                    <Badge count={unreadCount} style={{ marginLeft: 4 }} />
                  )}
                </span>
              ),
              children: null,
            },
            {
              key: 'starred',
              label: `已加星标`,
              children: null,
            },
          ]}
        />

        <List
          itemLayout="horizontal"
          dataSource={filteredMessages}
          locale={{
            emptyText: <Empty description="暂无消息" />,
          }}
          renderItem={(message: MessageItem) => (
            <List.Item
              actions={[
                <Dropdown
                  key="more"
                  menu={getMessageMenu(message)}
                  trigger={['click']}
                >
                  <Button type="text" icon={<MoreOutlined />} />
                </Dropdown>,
              ]}
              style={{
                backgroundColor: message.read ? '#fff' : '#f6f6f6',
                borderRadius: 4,
                marginBottom: 8,
                padding: '16px',
                cursor: 'pointer',
                border: message.read ? '1px solid #f0f0f0' : '1px solid #d9d9d9',
              }}
            >
              <List.Item.Meta
                avatar={
                  <Avatar
                    size={40}
                    style={{ backgroundColor: '#1890ff' }}
                  >
                    {message.sender.charAt(0).toUpperCase()}
                  </Avatar>
                }
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    {!message.read && (
                      <Badge
                        status="processing"
                        style={{ transform: 'scale(0.8)' }}
                      />
                    )}
                    <span style={{ fontWeight: message.read ? 'normal' : 'bold' }}>
                      {message.subject}
                    </span>
                    {message.starred && (
                      <StarOutlined style={{ color: '#faad14' }} />
                    )}
                    {message.attachments && message.attachments.length > 0 && (
                      <Tag color="blue">
                        {message.attachments.length} 个附件
                      </Tag>
                    )}
                  </div>
                }
                description={
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ color: '#666', fontSize: 14 }}>
                        发件人: {message.sender}
                      </span>
                      <span style={{ color: '#999', fontSize: 12 }}>
                        {new Date(message.createdAt).toLocaleString()}
                      </span>
                    </div>
                    <p style={{ margin: '8px 0 0 0', color: '#666', fontSize: 14 }}>
                      {message.content.length > 100
                        ? `${message.content.substring(0, 100)}...`
                        : message.content}
                    </p>
                  </div>
                }
              />
            </List.Item>
          )}
        />

        {filteredMessages.length === 0 && (
          <Empty
            description={
              searchText
                ? '没有找到匹配的消息'
                : activeTab === 'unread'
                ? '暂无未读消息'
                : activeTab === 'starred'
                ? '暂无星标消息'
                : '暂无消息'
            }
            style={{ marginTop: 48 }}
          />
        )}
      </Card>
    </div>
  );
};

export default MessagesPage;